import dfsFolder
import os
import shutil
import time
import logcat
def copy_files(dir,backup_root,initial_root):
    List=dfsFolder.dfs_traverse(dir)
    # print(List)
    # 先确定顶级根目录（如H:\）
    root_dir = initial_root
    # 计算当前目录相对于顶级根目录的路径
    relative_path = os.path.relpath(dir, root_dir)
    logcat.Logcat.d("ycopy", "当前目录："+dir)
    
    time.sleep(0.011)

    current_backup_dir = os.path.join(backup_root, relative_path)
    os.makedirs(current_backup_dir, exist_ok=True)
    folderName=List[0]
    childFolderList=List[1]
    fileList=List[2]
    for file in fileList:
        try:
            fileName=os.path.join(dir,file)
            targetName = os.path.join(current_backup_dir, file)
            shutil.copy(fileName,targetName)
            logcat.Logcat.d("ycopy", "copy "+fileName+" to "+targetName+" success")
            time.sleep(0.011)
        except:
            pass
    if childFolderList:
        for childFolder in childFolderList:
            # print(childFolder[0])#foldername
            targetDir=os.path.join(dir,childFolder[0])
            copy_files(targetDir,backup_root,initial_root)    
def runCopy(dir,backup_root):
    try:
        copy_files(dir,backup_root,dir)
    except Exception as e:
        logcat.Logcat.e("ycopy", "子线成发生严重错误："+str(e)+ " 目录："+dir+" 备份目录："+backup_root)

if __name__ == "__main__":
    # logcat.Logcat.d("1", "1")
    runCopy('H:\\','./bak')
    
    # List=dfsFolder.dfs_traverse('H:\\')
    # print(List)

